<?php

namespace app\admin\controller;

use think\Request;

class Shop extends Base
{

    /**
     * 产品分类
     */
    public function index()
    {
        $list = M('goods_cate a')
            ->order('a.id desc')->paginate('', false, page_param());
        $this->assign('list', $list);
        return $this->fetch();
    }

    //产品分类编辑
    public function index_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->index_store($request);
        }
        $id = I('id', 0);
        $list = M('goods_cate')->where('id', $id)->find();
        $this->assign('info', $list);
        return $this->fetch();
    }

    //产品分类删除
    public function index_del()
    {
        $params = input();
        $ids = explode(',', $params['id']);
        //查询产品列表是否有使用该分类
        $goods = M('goods')->where('goods_cate_id', 'in', $ids)->find();
        if (!empty($goods)) {
            return $this->ajaxReturn(1, '分类下有产品使用,请先删除该分类下产品');
        }
        $title = db('goods_cate')->where('id', 'in', $ids)->column('name');
        db('goods_cate')->where('id', 'in', $ids)->delete();
        add_sys_log('删除产品分类:' . implode(',', $title));
        return $this->ajaxReturn(0, '成功');
    }

    //产品分类编辑或添加提交
    public function index_store()
    {
        $params = input();
        unset($params['file']);
//        var_dump($params);die;
        $result = $this->validate(
            $params,
            ['name' => 'require|max:30',
            ],
            ['name.require' => '标题必填',
                'name.max' => '标题最多30个字符',
            ]
        );
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if ($params['id']) {
            db('goods_cate')->where('id', $params['id'])->update($params);
            add_sys_log('修改产品分类:' . $params['name']);
        } else {
            $params['admin_id'] = session('user_info')['id'];
            $params['create_time'] = time();
            db('goods_cate')->where('id', $params['id'])->insert($params);
            add_sys_log('添加产品分类:' . $params['name']);
        }
        return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/index'));
    }

    //产品分类修改状态
    public function index_status()
    {
        $params = input();
        db('goods_cate')->where('id', $params['id'])->update(['status' => $params['status']]);
        $title = db('goods_cate')->where('id', $params['id'])->value('name');
        add_sys_log('修改产品分类状态:' . $title);
        return json_encode(['info' => '成功', 'status' => 1]);
    }

    //产品列表
    public function product()
    {
        $where = [];
        $goods_cate_id = I('goods_cate_id', 0);
        $search = I('search', '');
        if (!empty($goods_cate_id)) {
            $where['a.goods_cate_id'] = $goods_cate_id;
        }
        if (!empty($search)) {
            $where['a.name'] = ['like', "%{$search}%"];
        }
        $export = I('export', 0);
        if ($export == 1) {
            $list_a = M('goods a')
                ->join('goods_cate b', 'a.goods_cate_id = b.id', 'left')
                ->field('a.*,b.name cate_name')
                ->where($where)
                ->order('a.id desc')
                ->select();
            $this->goods_export($list_a);
        }
        $list = M('goods a')
            ->join('goods_cate b', 'a.goods_cate_id = b.id', 'left')
            ->field('a.*,b.name cate_name')
            ->where($where)
            ->order('a.id desc')->paginate('', false, page_param());
        $cate = M('goods_cate')->where('status', 1)->select();
//        获取，产品型号b author:zj
        $goodsIds = array_column($list->items(), 'id');
        $goods_model_names = M('goods_model')->where('goods_id', 'in', $goodsIds)->select();
        $tmpArr = [];
        foreach ($goods_model_names as $v){
            if(!isset($tmpArr[$v['goods_id']])) $tmpArr[$v['goods_id']] = '';
            $tmpArr[$v['goods_id']] .= $v['model_name'].',';
        }
        $goods_model_names = $tmpArr;
        //获取，产品型号e author:zj
        $this->assign('list', $list);
        $this->assign('cate', $cate);
        $this->assign('goods_model_names', $goods_model_names);
        return $this->fetch();
    }

    //添加产品
    public function product_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->product_store($request);
        }
        $id = I('id', 0);
        $list =M('goods')->where('id', $id)->find();
        //分类
        $cate = M('goods_cate')->where('status', 1)->select();

        $goods_model_names = M('goods_model')->where('goods_id', $id)->select();
//        var_dump($goods_model_names);die;
        $this->assign('info', $list);
        $this->assign('cate', $cate);
        $this->assign('model', $goods_model_names);
        return $this->fetch();
    }

    //产品删除
    public function product_del()
    {
        $params = input();
        $ids = explode(',', $params['id']);
        $title = db('goods')->where('id', 'in', $ids)->column('name');
        db('goods')->where('id', 'in', $ids)->delete();
        db('goods_model')->where('goods_id', 'in', $ids)->delete();
        add_sys_log('删除产品:' . implode(',', $title));
        return $this->ajaxReturn(0, '成功');
    }

    //产品编辑或添加提交
    public function product_store()
    {
        $params = input();
        $result = $this->validate(
            $params,
            ['name' => 'require|max:50',
                'model' => 'require',
                'images' => 'require',
                'price' => 'require',
                'market_price' => 'require',
                'content' => 'require',
            ],
            ['name.require' => '标题必填',
                'name.max' => '标题最多50个字符',
                'model.require' => '模型不能为空',
                'images.require' => '图片不能为空',
                'price.require' => '价格不能为空',
                'market_price.require' => '市场价不能为空',
                'content.require' => '产品内容不能为空',
            ]
        );
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        $params['images'] = implode(',', $params['images']);


//        $params['model'] = serialize($tmpArr);
        //产品关联型号表b   author:zj

        //产品关联型号表e   author:zj
        $model = [];
        if($params['model'] && count($params['model']) > 0 ){
            $model = $params['model'];
        }
        if ($params['id']) {
            $id = $params['id'];
            unset($params['model']);
            db('goods')->where('id', $params['id'])->update($params);
            add_sys_log('修改产品:' . $params['name']);
        } else {
            $params['create_time'] = time();
            $id = M('goods')->insertGetId($params);
            add_sys_log('添加产品:' . $params['name']);
        }
        if(!empty($model)){
            $tmpArr = [];
            foreach ($model as $key=>$mv) {
//                $tmpArr[$mv] = $params['img'.$key];
                $tmpArr[] = ['model_name'=>$mv, 'img'=>$params['img'.$key],'goods_id'=>$id];
            }
            $this->goods_model_store($tmpArr, $id);
        }
        return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/product'));
    }

    //产品型号表   author:zj
    private function goods_model_store($models, $id)
    {
        //删除产品id关联的型号
        db('goods_model')->where('goods_id', $id)->delete();
        //插入产品关联的型号
        db('goods_model')->insertAll($models);

    }

    //课程型号表   author:zj
    private function course_model_store($models, $id)
    {
        //删除产品id关联的型号
        db('course_model')->where('course_id', $id)->delete();
        //插入产品关联的型号
        db('course_model')->insertAll($models);

    }

    //产品修改状态
    public function product_status()
    {
        $params = input();
        db('goods')->where('id', $params['id'])->update(['status' => $params['status']]);
        $title = db('goods')->where('id', $params['id'])->value('name');
        add_sys_log('修改产品状态:' . $title);
        return json_encode(['info' => '成功', 'status' => 1]);
    }

    //产品导出Excel
    public function goods_export($data)
    {
        set_time_limit(0);
        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">产品编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">产品分类</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">产品名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">产品型号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">产品价格</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">产品市场价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">产品状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">添加时间</td>';
        $strTable .= '</tr>';
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                if ($val['status'] == 1) {
                    $status = '开启';
                } else {
                    $status = '关闭';
                }
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['id'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['cate_name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['model'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['price'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['market_price'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $status . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d H:i', $val['create_time']) . '</td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .= '</table>';
        unset($list);
        $name = '产品列表';
        downloadExcel($strTable, $name);
        exit();
    }

    //课程列表
    public function course()
    {
        $where = [];
        $search = I('search', '');
        if (!empty($search)) {
            $where['a.name'] = ['like', "%{$search}%"];
        }
        $export = I('export', 0);
        if ($export == 1) {
            $list_a = M('course a')
                ->where($where)
                ->order('a.id desc')
                ->select();
            $this->course_export($list_a);
        }
        $list = M('course a')
            ->where($where)
            ->order('a.id desc')
            ->paginate('', false, page_param());

        //获取，产品型号b author:zj
        $courseIds = array_column($list->items(), 'id');
        $course_model_names = M('course_model')->where('course_id', 'in', $courseIds)->select();
        $tmpArr = [];
        foreach ($course_model_names as $v){
            if(!isset($tmpArr[$v['course_id']])) $tmpArr[$v['course_id']] = '';
            $tmpArr[$v['course_id']] .= $v['model_name'].',';
        }
        $course_model_names = $tmpArr;
        //获取，产品型号e author:zj
        $this->assign('list', $list);
        $this->assign('course_model_names', $course_model_names);
        return $this->fetch();
    }

    //课程编辑
    public function course_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->course_store($request);
        }
        $id = I('id', 0);
        $list = M('course')->where('id', $id)->find();

        $course_model_names = M('course_model')->where('course_id', $id)->select();

        $this->assign('info', $list);
        $this->assign('model', $course_model_names);
        return $this->fetch();
    }

    //课程删除
    public function course_del()
    {
        $params = input();
        $ids = explode(',', $params['id']);
        $title = db('course')->where('id', 'in', $ids)->column('name');
        db('course')->where('id', 'in', $ids)->delete();
        db('course_model')->where('course_id', 'in', $ids)->delete();
        add_sys_log('删除课程:' . implode(',', $title));
        return $this->ajaxReturn(0, '成功');
    }

    //课程编辑或添加提交
    public function course_store()
    {
        $params = input();

        $result = $this->validate(
            $params,
            ['name' => 'require|max:50',
                'course_time' => 'require',
                'image' => 'require',
                'price' => 'require',
                'content' => 'require',
            ],
            ['name.require' => '课程名称必填',
                'title.max' => '课程名称最多50个字符',
                'course_time.require' => '课程时间不能为空',
                'image.require' => '课程封面不能为空',
                'price.require' => '课程单价不能为空',
                'content.require' => '课程详情不能为空',
            ]
        );
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        $params['course_time'] = strtotime($params['course_time']);

        if($params['model'] && count($params['model']) > 0 ){
            $tmpArr = [];
            foreach ($params['model'] as $key=>$mv) {
                $tmpArr[] = ['model_name'=>$mv, 'img'=>$params['img'.$key],'course_id'=>$params['id']];
            }
        }
        //产品关联型号表b   author:zj
        $this->course_model_store($tmpArr, $params['id']);
        unset($params['model']);
        //产品关联型号表e   author:zj

        if ($params['id']) {
            db('course')->where('id', $params['id'])->update($params);
            add_sys_log('修改课程:' . $params['name']);
        } else {
            $params['create_time'] = time();
            db('course')->where('id', $params['id'])->insert($params);
            add_sys_log('新增课程:' . $params['name']);
        }
        return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/course'));
    }

    //课程修改状态
    public function course_status()
    {
        $params = input();
        db('course')->where('id', $params['id'])->update(['status' => $params['status']]);
        $title = db('course')->where('id', $params['id'])->value('name');
        add_sys_log('修改课程状态:' . $title);
        return json_encode(['info' => '成功', 'status' => 1]);
    }

    //课程导出Excel
    public function course_export($data)
    {
        set_time_limit(0);
        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">课程编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">课程名称</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:*">课程时间</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">单价</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">添加时间</td>';
        $strTable .= '</tr>';
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                if ($val['status'] == 1) {
                    $status = '开启';
                } else {
                    $status = '关闭';
                }
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['id'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d H:i', $val['course_time']) . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['price'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $status . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . date('Y-m-d H:i', $val['create_time']) . '</td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .= '</table>';
        unset($list);
        $name = '课程列表';
        downloadExcel($strTable, $name);
        exit();
    }

    //产品型号表 author:zj //todo,作废
    public function product_type()
    {
        $list = M('goods_model')->paginate();
        $this->assign('list', $list);
        return $this->fetch();
    }

    //产品型号表编辑页面  author:zj //todo,作废
    public function product_type_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->product_type_store($request);
        }
        $id = I('id', 0);
        $list = M('goods_model')->where('id', $id)->find();
        $this->assign('info', $list);
        return $this->fetch();
    }

    //产品型号表编辑或添加提交  author:zj //todo,作废
    private function product_type_store()
    {
        $params = input();
        unset($params['file']);
        $result = $this->validate(
            $params,
            ['model_name' => 'require|max:30',
            ],
            ['model_name.require' => '型号名称',
                'name.max' => '型号名称最多30个字符',
            ]
        );
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if ($params['id']) {
            db('goods_model')->where('id', $params['id'])->update($params);
            add_sys_log('修改产品型号:' . $params['model_name']);
        } else {
            db('goods_model')->where('id', $params['id'])->insert($params);
            add_sys_log('添加产品型号:' . $params['model_name']);
        }
        return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/product_type'));
    }

    public function banner()
    {
        $list = db('shop_slide')->order('sort desc')->paginate();
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function banner_edit(Request $request)
    {
        if ($request->isPost()) {
            return $this->banner_store($request);
        }

        $id = I('id', 0);
        $list = M('shop_slide')->where('id', $id)->find();
        $this->assign('info', $list);
        return $this->fetch();
    }

    private function banner_store()
    {
        $params = input();
        unset($params['file']);
        $result = $this->validate(
            $params,
            [
                'type' => 'require',
                'relation_id'=>'require'
            ],
            [
                'type.require' => '类型',
                'relation_id.require' => '关联商品或者课程id',
            ]
        );
        if (true !== $result) {
            return $this->ajaxReturn(1, $result);
        }
        if($params['type'] == 1 && M('goods')->find($params['relation_id'])){

        }elseif($params['type'] == 2 && M('course')->find($params['relation_id'])){

        }else{
            return $this->ajaxReturn(1, "非法操作！");
        }
        if ($params['id']) {
            db('shop_slide')->where('id', $params['id'])->update($params);
        } else {
            unset($params['id']);
            db('shop_slide')->insert($params);
        }
        return $this->ajaxReturn(0, "成功", url(CONTROLLER_NAME . '/banner'));
    }

    public function banner_del()
    {
        $params = input();
        $ids = explode(',', $params['id']);
        db('shop_slide')->where('id', 'in', $ids)->delete();
        return $this->ajaxReturn(0, '成功');
    }
    //是否开启商城
    public function shop_set(){
        if (request()->isPost()) {
            $is_open_shop = input('is_open_shop','off');
            if($is_open_shop == 'on'){
                $status = 1;
            }else{
                $status = 0;
            }
            M('admin_server')->where('id', 1)->update(['is_open_shop'=>$status]);
            return $this->ajaxReturn(0, '成功');
        }
        $list = M('admin_server')->where('id', 1)->find();
        $this->assign('info', $list);
        return $this->fetch();
    }
    public function update_open_shop()
    {

    }


}